$(function() {
  let userInfo = getCookie('user') || ''
  let type = userInfo.type
  let openid = userInfo.openid
  let userv1info = getCookie('userv1info') || ''
  let userbindinfo = getCookie('userbindinfo') || ''
  const api = 'http://api.zymk.cn/app_api/v3/'
  const user = '/user/v1/'
  const clearsina = '/clearsina'
  const mkxqspan = $('.mkxqspan'),
    qqspan = $('.qqspan'),
    wxspan = $('.wxspan'),
    sinaspan = $('.sinaspan'),
    mobilespan = $('.mobilespan'),
    mailspan = $('.mailspan');
  //改变用户绑定信息的说明
  function showInfo(data) {
    data.mkxq ? mkxqspan.text('已绑定') : mkxqspan.text('未绑定')
    data.qq ? qqspan.text('已绑定') : qqspan.text('未绑定')
    data.sian ? sinaspan.text('已绑定') : sinaspan.text('未绑定')
    data.weixin ? wxspan.text('已绑定') : wxspan.text('未绑定')
    if(!data.mkxq) {
      mailspan.text('未绑定')
      mobilespan.text('未绑定')
    }
  }
  //改变用户绑定信息的说明
  function showV1info(data) {
    data.user.email ? mailspan.text('已绑定') : mailspan.text('未绑定')
    data.user.mobile ? mobilespan.text('已绑定') : mobilespan.text('未绑定')
    data.user.username ? mkxqspan.text('已绑定') : mkxqspan.text('未绑定')
  }
  /**
   * @param {token} token为getbinduserinfo接口返回的mkxq里的返回值
   */
  function getV1Info(token) {
    $.ajax({
      url: user + 'getuserinfo/',
      type: 'POST',
      data: {
        token: token
      },
      success: function(res) {
        let data = JSON.parse(res)
        setCookie('userv1info', JSON.stringify(data.data), 365)
        showV1info(data.data)
      }
    })
  }
  // 获得用户的绑定信息
  function getUserBind() {
    console.log(13)
    $.ajax({
      url: api + 'getuserbindinfo/?type=' + type + '&openid=' + openid,
      dataType: 'jsonp',
      jsonp: 'callback',
      success: function(res) {
        if(res.status === 0) {
          setCookie('userbindinfo', JSON.stringify(res.data), 365)
          showInfo(res.data)
          res.data.mkxq && getV1Info(res.data.mkxq)
        }
      }
    })
  }
  //三方相关
  function thirdCallback() {
    var search = location.search;
    var matchType = search.match(/(type|state)\=([a-z0-9]+)/i);
    var type_tp = matchType ? matchType[2].toLocaleLowerCase() : false;
    var token = '',
      lastargs = '';

    if(!type_tp) {
      // layer.msg('未找到登录信息，请重新再试', { time: 1500 })
      return;
    }

    switch(type_tp) {
      case 'qq':
        var qqMath = location.hash.match(/access_token=([^\&]+)/i);
        token = qqMath ? qqMath[1] : false;
        oldloginvar = type + '#access_token=' + token;
        break;
      case 'sina':
        var sinaMath = search.match(/code=([a-z0-9]+)/i);
        token = sinaMath ? sinaMath[1] : false;
        break;
      case 'weixin':
        var wixinMath = search.match(/code=([a-z0-9]+)/i);
        token = wixinMath ? wixinMath[1] : false;
        break;
    }

    if(!token) {
      // this.layer('simple', {
      //   msg: '登录授权失败，请重新刷新再试!'
      // }, 1000)
      return;
    }
    var openid = userInfo.openid;
    var type = userInfo.type;
    console.log('token', token, type, openid, type_tp)
    console.log('11', type_tp)
    console.log(userbindinfo)
    if(userbindinfo[type_tp]) {
      // unbinduser
      unBindUser(type, openid, type_tp, token)
      console.log('jiebang')
    } else {
      // 绑定逻辑
      console.log('bangding')
      bindUser(type, openid, type_tp, token)
    }
  }
  // 解绑账号函数
  function unBindUser(type, openid, target_type, target_token) {
    $.ajax({
      url: api + 'unbinduser/',
      data: {
        type: type,
        openid: openid,
        target_type: target_type,
        target_token: target_token,
        client: 'pc'
      },
      dataType: 'jsonp',
      jsonp: 'callback',
      success: function(res) {
        console.log(res)
        if(res.status === 0) {
          if(userInfo.type != target_type) {
            setCookie('userbindinfo', '', -1);
            setTimeout(() => {
              location.href = location.origin + '/personalset/bindAccount';
            }, 1500)
          } else {
            console.log('退出登录')
          }
        } else {
          console.log(res.msg)
          setTimeout(() => {
            location.href = location.origin + '/personalset/bindAccount';
          }, 1500)
        }
      }
    })
  };
  // 绑定账号函数
  function bindUser(type, openid, target_type, target_token) {
    $.ajax({
      url: api + 'binduser/?type=' + type + '&openid=' + openid + '&target_type=' + target_type + '&target_token=' + target_token + '&client=pc',
      dataType: 'jsonp',
      jsonp: 'callback',
      success: function(res) {
        if(res.status === 0) {
          setCookie('userbindinfo', '', -1);
        } else {
          if(target_type === 'sina') {
            $.ajax({
              url: clearsina,
              type: 'POST',
              data: { access_token: res.data.sina_access_token },
              success: function(res) {}
            })
          }
          console.log(res.msg)
        }
        setTimeout(() => {
          location.href = location.origin + '/personalset/bindAccount';
        }, 1500)
      }
    })
  }
  thirdCallback();
  if(!userbindinfo) {
    console.log(userbindinfo)
    getUserBind()
  } else {
    showInfo(userbindinfo)
    userv1info && showV1info(userv1info)
  }
  //添加跳转路由点击事件
  $('.bindBox').on('click', 'div', function() {
    let flag = $(this).data('flag')
    let userbindinfo = getCookie('userbindinfo') || ''
      // 此处跳转需用lacation.origin跳转，无法用host进行跳转
    switch(flag) {
      case 'tel':
        window.location.href = location.origin + '/personalset/modifypage/' + flag
        break;
      case 'email':
        console.log('email')
        window.location.href = location.origin + '/personalset/modifypage/' + flag
        break;
      case 'mkxq':
        window.location.href = location.origin + '/personalset/modifypage/' + flag
        break;
      case 'qq':
        if(userbindinfo.mkxq) {
          if(userbindinfo.qq && userInfo.type !== 'qq' && confirm('确定解绑qq账号吗？')) {
            url = 'https://graph.qq.com/oauth2.0/authorize?client_id=101369285&response_type=token&scope=get_user_info&redirect_uri=' + encodeURIComponent(location.href + '?type=qq')
            location.href = url;
          } else if(userbindinfo.qq && userInfo.type === 'qq' && confirm('确定解绑qq账号吗？,如果解绑该账号会被注销。')) {
            url = 'https://graph.qq.com/oauth2.0/authorize?client_id=101369285&response_type=token&scope=get_user_info&redirect_uri=' + encodeURIComponent(location.href + '?type=qq')
            location.href = url;
          } else if(!userbindinfo.qq) {
            url = 'https://graph.qq.com/oauth2.0/authorize?client_id=101369285&response_type=token&scope=get_user_info&redirect_uri=' + encodeURIComponent(location.href + '?type=qq')
            location.href = url;
          }
        } else {
          console.log('您需要先绑定手机或者邮箱')
        }
        break;
      case 'wx':
        console.log('wx')
        break;
      case 'sina':
        if(userbindinfo.mkxq) {
          if(userbindinfo.sina && confirm('确定解绑sina账号吗？')) {
            url = 'https://api.weibo.com/oauth2/authorize?client_id=199818462&redirect_uri=' + encodeURIComponent(location.href + '?type=sina')
            location.href = url;
          } else if(!userbindinfo.sina) {
            url = 'https://api.weibo.com/oauth2/authorize?client_id=199818462&redirect_uri=' + encodeURIComponent(location.href + '?type=sina')
            location.href = url;
          } else if(userbindinfo.sina && userInfo.type === 'sina' && confirm('确定解绑sina账号吗？,如果解绑该账号会被注销。')) {

          } else {
            return
          }
        } else {
          console.log('您需要先绑定手机或者邮箱')
        }
        break;
    }
  })
})